package com.yupi.longojbackendjudgeservice.judge;

import cn.hutool.json.JSONUtil;
import com.yupi.longojbackendcommon.common.ErrorCode;
import com.yupi.longojbackendcommon.exception.BusinessException;
import com.yupi.longojbackendjudgeservice.judge.codesandbox.CodeSandbox;
import com.yupi.longojbackendjudgeservice.judge.codesandbox.CodeSandboxFactory;
import com.yupi.longojbackendjudgeservice.judge.codesandbox.CodeSandboxProxy;
import com.yupi.longojbackendjudgeservice.judge.strategy.JudgeContext;
import com.yupi.longojbackendmodel.codesandbox.ExecuteCodeRequest;
import com.yupi.longojbackendmodel.codesandbox.ExecuteCodeResponse;
import com.yupi.longojbackendmodel.codesandbox.JudgeInfo;
import com.yupi.longojbackendmodel.dto.question.JudgeCase;
import com.yupi.longojbackendmodel.entity.Question;
import com.yupi.longojbackendmodel.entity.QuestionSubmit;
import com.yupi.longojbackendmodel.enums.QuestionSubmitStatusEnum;
import com.yupi.longojbackendserviceclient.service.QuestionFeignClient;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
@Service
/**
 * 判题服务实现类
 */
public class JudgeServiceImpl implements JudgeService {
    @Autowired
    private QuestionFeignClient questionFeignClient;
    @Autowired
    private JudgeManager judgeManager;
    @Value("${codeSandbox.type:example}")
    private String type;
    @Override
    public QuestionSubmit doJudge(Long questionSubmitId) {
        //1传入题目的提交id，获取到对应的题目，提交信息（包含代码，编程语言等）
        QuestionSubmit questionSubmit = questionFeignClient.questionSubmitById(questionSubmitId);
        if( questionSubmit == null) {
           throw  new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionFeignClient.qusetionById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        Integer status = questionSubmit.getStatus();
        //2如果题目提交状态不为等待中，就不用重复执行了
      if (!status.equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"该题目正在判题中");
      }

       //3.更改判题（题目提交的状态为判题中，防止重复执行，也能让用户即时看到状态）
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
      questionSubmitUpdate.setId(questionSubmitId);
      //todo 观察这里其他信息是不是更新为空了
      questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean result = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"更改状态失败");
        }
        //4.调用沙箱，获取到执行结果
        //TODO: 调用判题机进行判题  return null;
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        String judgeCaseStr = question.getJudgeCase();
        //第一种
       /* Gson gson = new Gson();
        List<JudgeCase> judgeCaseList = gson.fromJson(judgeCaseStr, new TypeToken<List<JudgeCase>>() {
        }.getType());*/
        //第二种
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(judgeCase -> judgeCase.getInput())
                .collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse=codeSandbox.excuteCode(executeCodeRequest);
        List<String> outputList = executeCodeResponse.getOutput();
        JudgeInfo judgeInfo = executeCodeResponse.getJudgeInfo();
        //5.根据沙箱的执行结果，设置题目的判题状态和信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeInfo(judgeInfo);
        judgeContext.setQuestion(question);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestionSubmit(questionSubmit);
        JudgeInfo judgeInfoUpdate = judgeManager.doJudge(judgeContext);
        //修改数据库中的判题结果
         questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfoUpdate));
        result = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"題目状态更新失败");
        }

        QuestionSubmit questionSubmitResult = questionFeignClient.questionSubmitById(questionSubmitId);
        return questionSubmitResult;
    }
}
